package com.itmuch.content_center.service.share;


import com.itmuch.content_center.dao.share.ShareMapper;
import com.itmuch.content_center.domain.dto.share.ShareDTO;
import com.itmuch.content_center.domain.dto.user.UserDTO;
import com.itmuch.content_center.domain.entity.share.Share;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareService {

    private final ShareMapper shareMapper;

    private final RestTemplate restTemplate;

    private final DiscoveryClient discoveryClient;

    public ShareDTO findById(Integer id){
        Share share = shareMapper.selectByPrimaryKey(id);

        Integer userId = share.getUserId();

//        ResponseEntity<String> forEntity = restTemplate.getForEntity(
//                "http://localhost:8081/users/{id}", String.class, 2
//        );


        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");

        List<String> targetUrl = instances.stream().map(instance -> instance.getUri().toString()+"/users/{id}").collect(Collectors.toList());

        int i = ThreadLocalRandom.current().nextInt(targetUrl.size());

        log.info("请求的目标地址：{}", targetUrl.get(i));

        UserDTO userDTO = this.restTemplate.getForObject(targetUrl.get(i), UserDTO.class, userId);


        ShareDTO shareDto = new ShareDTO();

        BeanUtils.copyProperties(share,shareDto);

        shareDto.setWxNickname(userDTO.getWxNickname());

        return shareDto;
    }

}
